from flask import Blueprint, request, jsonify
from .. import db
from ..models import Bill

bills_bp = Blueprint('bills', __name__)

@bills_bp.route('/add-bill', methods=['POST'])
def add_bill():
    data = request.get_json()
    required_fields = ['user_id', 'amount', 'category', 'categoryType', 'date']
    if not all(data.get(field) for field in required_fields):
        return jsonify({'error': '参数不完整'}), 400

    bill = Bill(**{field: data.get(field) for field in ['user_id', 'amount', 'category', 'categoryType', 'note', 'date']})
    db.session.add(bill)
    db.session.commit()
    return jsonify({'message': '账单添加成功'})

@bills_bp.route('/get-bills', methods=['POST'])
def get_bills():
    data = request.get_json()
    user_id = data.get('user_id')
    if not user_id:
        return jsonify({'error': '缺少 user_id'}), 400

    bills = Bill.query.filter_by(user_id=user_id).order_by(Bill.date.desc()).all()
    result = [{
        'id': b.id,
        'amount': b.amount,
        'category': b.category,
        'categoryType': b.categoryType,
        'note': b.note,
        'date': b.date
    } for b in bills]
    return jsonify({'bills': result})

@bills_bp.route('/update-bill', methods=['POST'])
def update_bill():
    data = request.get_json()
    bill = Bill.query.filter_by(id=data.get('id'), user_id=data.get('user_id')).first()
    if not bill:
        return jsonify({'error': '账单不存在或无权限'}), 404

    for field in ['amount', 'category', 'categoryType', 'note', 'date']:
        setattr(bill, field, data.get(field, getattr(bill, field)))

    db.session.commit()
    return jsonify({'message': '账单更新成功'})

@bills_bp.route('/delete-bill', methods=['POST'])
def delete_bill():
    data = request.get_json()
    bill = Bill.query.filter_by(id=data.get('id'), user_id=data.get('user_id')).first()
    if not bill:
        return jsonify({'error': '账单不存在或无权限'}), 404

    db.session.delete(bill)
    db.session.commit()
    return jsonify({'message': '账单删除成功'})
